package com.apes.autoparts.masterdata.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.util.MapUtil;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @ClassName Manager
 * @Description TODO
 * @Author pengyb
 * @Date 2019/11/25 13:47
 * @Version 1.0
 **/
@Component
public class EpcMasterDataManager extends DomainService {
    public final String CONST_SAVE = "S";
    public final String CONST_UPDATE = "U";

    /**
     * 同步新框架
     *
     * @param body
     */
    public void synEsb(String method, Object body) {
        //同步至新系统
        Object invoke = invoke(method, body);
        JSONObject header = JSONObject.parseObject(invoke.toString()).getJSONObject("header");
        if (!"success".equals(header.get("code"))) throw new RuntimeException(header.getString("message"));
    }

    /**
     * 获取erp对应数据版本号(时间戳)
     *
     * @param body
     * @param method
     * @return
     */
    public String getVersion(String method, Object body) {
        Object getDate = invoke("pi.yyerpLocal.invoke", mapper("body", body, "headers", MapUtil.mapper("method", method)));
        JSONObject parseObject = JSONObject.parseObject(getDate.toString());
        if (!parseObject.getBoolean("success")) throw new RuntimeException(parseObject.getString("msg"));
        JSONArray parseArray = JSONArray.parseArray(parseObject.get("obj").toString());
        if (parseArray==null||parseArray.size()==0) throw new RuntimeException("ERP查无此数据，更新失败！");
        JSONObject data = (JSONObject) (parseArray).stream().findAny().get();
        return data.getString("TS01");
    }

    /**
     * 同步erp
     *
     * @param body
     * @param method
     */
    public void synErp(String method,Object body ) {
        Map data = mapper("body", body, "headers", MapUtil.mapper("method", method));
        Object result = invoke("pi.yyerpLocal.invoke", data);
        JSONObject resultJo = JSONObject.parseObject(result.toString());
        if (!resultJo.getBoolean("success")) throw new RuntimeException(resultJo.getString("msg"));
    }
}
